﻿using System;
namespace YanZhiwei.DotNet2.Utilities.Base
{
    /// <summary>
    /// Lazy 基于.NET 2.0的实现帮助类
    /// <para>参考：http://stackoverflow.com/questions/3207580/implementation-of-lazyt-for-net-3-5 </para>
    /// </summary>
    /// <typeparam name="T">泛型</typeparam>
    public sealed class ThreadSafeLazy<T>
    {
        private readonly object padlock = new object();
        private readonly Func<T> createValue;
        private bool isValueCreated;
        private T value;
        /// <summary>
        /// 获取初始化值
        /// </summary>
        public T Value
        {
            get
            {
                if (!isValueCreated)
                {
                    lock (padlock)
                    {
                        if (!isValueCreated)
                        {
                            value = createValue();
                            isValueCreated = true;
                        }
                    }
                }
                return value;
            }
        }
        /// <summary>
        /// 是否初始化
        /// </summary>
        public bool IsValueCreated
        {
            get
            {
                lock (padlock)
                {
                    return isValueCreated;
                }
            }
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="createValue">委托</param>
        public ThreadSafeLazy(Func<T> createValue)
        {
            if (createValue == null) throw new ArgumentNullException("createValue");
            this.createValue = createValue;
        }
        /// <summary>
        /// ToString
        /// </summary>
        /// <returns>String</returns>
        public override string ToString()
        {
            return Value.ToString();
        }
    }
}